$(function(){
   //选取文件时读取文件信息
   $("#fileform .select").bind("change", function(){
       var file = $(this).get(0).files;
        if (file.length>0){
            $(".info").append('<li class="header clearfix">'
                                    +'<span class="name">文件名</span>'
                                    +'<span class="size">大小</span></li>');
            for(var i = 0; i < file.length; i++){
                var fileSize = 0;
                if (file[i].size > 1024 * 1024)
                    fileSize = (Math.round(file[i].size / (1024 * 1024))).toString() + 'MB';
                else
                    fileSize = (Math.round(file[i].size / 1024)).toString() + 'KB';
                $(".info").append('<li class="single clearfix">'
                                        +'<span class="name">'+file[i].name+'</span>'
                                        +'<span class="size">'+fileSize+'</span>'
                                        +'<a href="#" class="delete"></a></li>');
            }
        }
   });
   
   //上传文件
   $("#fileform .submit").click(function(){
        var xhr = new XMLHttpRequest();
        var fd = new FormData($("#fileform").get(0));

        /* event listners */
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        /* Be sure to change the url below to the url of your upload server side script */
        xhr.open("POST", "index.php");
        xhr.send(fd);       
   }); 
});

function uploadProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
    console.log(percentComplete.toString());
    document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
  }
  else {
    document.getElementById('progressNumber').innerHTML = 'unable to compute';
  }
}

function uploadComplete(evt) {
  /* This event is raised when the server send back a response */
  console.log(evt.target.responseText);
}

function uploadFailed(evt) {
  console.log("There was an error attempting to upload the file.");
}

function uploadCanceled(evt) {
  console.log("The upload has been canceled by the user or the browser dropped the connection.");
}  